package com.zxy.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zxy.util.Constant;
import com.zxy.mapper.ReportMapper;

import com.zxy.pojo.dto.*;
import com.zxy.pojo.entity.CourseContract;
import com.zxy.pojo.vo.*;
import com.zxy.service.ReportService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.util.*;


@Slf4j
@Service
public class ReportServiceImpl implements ReportService {
    @Autowired
    private ReportMapper reportMapper;

    //客户统计列表展示
    @Override
    public CourseContractResponseVO<CourseContract> contractStatisticsList(CustomerDTO dto) {
        Page<CourseContract> page = new Page<>(dto.getPageNum(), dto.getPageSize());
        Page<CourseContract> pages = reportMapper.contractStatisticsList(page,dto);
        CourseContractResponseVO<CourseContract> responseVO = new CourseContractResponseVO<>();
        responseVO.setTotal(pages.getTotal());
        responseVO.setRows(pages.getRecords());
        responseVO.setCode(Constant.SUCCESS);
        responseVO.setMsg(Constant.MSG);
        responseVO.setParams(null);
        return responseVO;
    }

    //客户统计数据表
    @Override
    public ReportVo contractStatistics(LocalDate beginCreateTime, LocalDate endCreateTime) {
        List<HashMap<String, String>> mapList = reportMapper.contractStatistics(beginCreateTime, endCreateTime);
        String[] timeArray = mapList.stream()
                .map(map -> String.valueOf(map.get(Constant.TIME)))
                .toArray(String[]::new);
        String[] addcount = mapList.stream().map(s -> String.valueOf(s.get(Constant.ADD))).toArray(String[]::new);
        String[] total = mapList.stream().map(s -> String.valueOf(s.get(Constant.TOTAL))).toArray(String[]::new);
        ReportVo reportVo = new ReportVo();
        reportVo.setXAxis(timeArray);
        ReportDetailVo detailVo = new ReportDetailVo();
        detailVo.setName(Constant.ADDUSER);
        detailVo.setData(total);
        ReportDetailVo detailVo1 = new ReportDetailVo();
        detailVo1.setName(Constant.SUM);
        detailVo1.setData(addcount);
        ArrayList<ReportDetailVo> detailVos = new ArrayList<>();
        detailVos.add(detailVo1);
        detailVos.add(detailVo);
        reportVo.setSeries(detailVos);
        return reportVo;
    }

    //学科客户分布  参考页面都没有数据-------------> //TODO 页面没有返回数据 猜的
    @Override
    public ReportSubjectDTO subjectStatistics(LocalDate beginCreateTime, LocalDate endCreateTime) {
        List<HashMap<String, Objects>> mapList = reportMapper.subjectStatistics(beginCreateTime, endCreateTime);
        String[] subjects = mapList.stream().map(s -> String.valueOf(s.get("subject"))).toArray(String[]::new);
        String[] count = mapList.stream().map(s -> String.valueOf(s.get("count"))).toArray(String[]::new);
        String[] percentages = mapList.stream().map(s -> String.valueOf(s.get(" percentage"))).toArray(String[]::new);
        ReportSubjectDTO reportSubjectDTO = new ReportSubjectDTO();
        reportSubjectDTO.setSubject(subjects);
        reportSubjectDTO.setCount(count);
        reportSubjectDTO.setPercentage(percentages);
        return reportSubjectDTO;
    }

    //销售列表展示
    @Override
    public CourseContractResponseVO<deptStatisticsListVo> deptStatisticsList(LocalDate pathStartDate,LocalDate pathEndDate,PageDTO dto) {
        Page<CourseContract> page = new Page<>(dto.getPageNum(), dto.getPageSize());
        Page<deptStatisticsListVo> listVoPage = reportMapper.deptStatisticsList(page, dto);
        log.info("数据为listVoPage:{}",listVoPage.getRecords());
        List<deptStatisticsListVo> records = listVoPage.getRecords();
        for (deptStatisticsListVo record : records) {
            record.setTotal_amount(record.getTotal());}
        CourseContractResponseVO<deptStatisticsListVo> responseVO = new CourseContractResponseVO<>();
        responseVO.setTotal(listVoPage.getTotal());
        responseVO.setRows(records);
        responseVO.setCode(Constant.SUCCESS);
        responseVO.setMsg(Constant.MSG);
        responseVO.setParams(null);
        log.info("转换后的数据为:{}",responseVO);
        return responseVO;
    }

    //销售列表展示 归属人 =====>//TODO 页面没有返回数据 猜的
    @Override
    public CourseContractResponseVO<deptStatisticsListVo> ownerShipStatisticsList(LocalDate pathStartDate, LocalDate pathEndDate, PageDTO dto) {
        Page<CourseContract> page = new Page<>(dto.getPageNum(), dto.getPageSize());
        Page<deptStatisticsListVo> listVoPage = reportMapper.ownerShipStatisticsList(page, dto);
        List<deptStatisticsListVo> records = listVoPage.getRecords();
        for (deptStatisticsListVo record : records) {
            record.setTotal_amount(record.getTotal());}
        CourseContractResponseVO<deptStatisticsListVo> responseVO = new CourseContractResponseVO<>();
        responseVO.setTotal(listVoPage.getTotal());
        responseVO.setRows(records);
        responseVO.setCode(Constant.SUCCESS);
        responseVO.setMsg(Constant.MSG);
        responseVO.setParams(null);
        return responseVO;
    }

    //销售列表 归属渠道 TODO 页面没有返回数据 猜的
    @Override
    public CourseContractResponseVO<deptStatisticsListVo> channelStatisticsList(LocalDate pathStartDate, LocalDate pathEndDate, PageDTO dto) {
        Page<CourseContract> page = new Page<>(dto.getPageNum(), dto.getPageSize());
        Page<deptStatisticsListVo> listVoPage = reportMapper.hannelStatisticsList(page, dto);
        List<deptStatisticsListVo> records = listVoPage.getRecords();
        for (deptStatisticsListVo record : records) {
            record.setTotal_amount(record.getTotal());}
        CourseContractResponseVO<deptStatisticsListVo> responseVO = new CourseContractResponseVO<>();
        responseVO.setTotal(listVoPage.getTotal());
        responseVO.setRows(records);
        responseVO.setCode(Constant.SUCCESS);
        responseVO.setMsg(Constant.MSG);
        responseVO.setParams(null);
        return responseVO;
    }
    //销售统计
    @Override
    public ReportVo salesStatistics(LocalDate beginCreateTime, LocalDate endCreateTime) {
        List<HashMap<String, Objects>> maps = reportMapper.salesStatistics(beginCreateTime, endCreateTime);
        String[] times = maps.stream().map(s -> String.valueOf(s.get("time"))).toArray(String[]::new);
        String[] amounts = maps.stream().map(s -> String.valueOf(s.get(Constant.AMOUNT))).toArray(String[]::new);
        ReportVo reportVo = new ReportVo();
        reportVo.setXAxis(times);
        ReportDetailVo detailVo = new ReportDetailVo();
        detailVo.setName(Constant.NAME);
        detailVo.setData(amounts);
        ArrayList<ReportDetailVo> detailVos = new ArrayList<>();
        detailVos.add(detailVo);
        reportVo.setSeries(detailVos);
        return reportVo;
    }

    //线索统计 分页展示
    @Override
    public CourseContractResponseVO<ClueDetailVo> cluesStatistics(CluesPageNumDTO dto) {
        Page<ClueDetailVo> page = new Page<>(dto.getPageNum(), dto.getPageSize());
        Page<ClueDetailVo> pages = reportMapper.cluesStatistics(page, dto);
        log.info("得到的数据是:{}",pages.getRecords());
        CourseContractResponseVO<ClueDetailVo> responseVO = new CourseContractResponseVO<>();
        responseVO.setTotal(pages.getTotal());
        responseVO.setRows(pages.getRecords());
        responseVO.setCode(Constant.SUCCESS);
        responseVO.setMsg(Constant.MSG);
        responseVO.setParams(null);
        return responseVO;

    }



    @Override
    public VulnerabilityMapResponseVO getVulnerabilityMap(LocalDate beginDate, LocalDate endDate) {
        log.info("查询漏洞统计地图数据，时间范围：{} 至 {}", beginDate, endDate);

        // 1. 查询各统计数据（实际业务中需根据表结构调整查询条件）
        Integer cluesNums = reportMapper.countCluesByDateRange(beginDate, endDate);
        Integer effectiveCluesNums = reportMapper.countEffectiveCluesByDateRange(beginDate, endDate);
        Integer businessNums = reportMapper.countBusinessByDateRange(beginDate, endDate);
        Integer contractNums = reportMapper.countContractByDateRange(beginDate, endDate);

        // 2. 封装响应数据
        VulnerabilityMapResponseVO responseVO = new VulnerabilityMapResponseVO();
        VulnerabilityMapResponseVO.VulnerabilityData data = new VulnerabilityMapResponseVO.VulnerabilityData();
        data.setCluesNums(cluesNums);
        data.setEffectiveCluesNums(effectiveCluesNums);
        data.setBusinessNums(businessNums);
        data.setContractNums(contractNums);
        responseVO.setData(data);

        return responseVO;
    }

    @Override
    public List<BusinessChangeStatsVo> businessChangeStatistics(LocalDate beginCreateTime, LocalDate endCreateTime) {
        log.info("查询业务变更统计数据，时间范围：{} 至 {}", beginCreateTime, endCreateTime);
        List<BusinessChangeStatsVo> result = reportMapper.businessChangeStatistics(beginCreateTime, endCreateTime);
        log.info("业务变更统计数据查询结果数量：{}", result != null ? result.size() : 0);

        // 如果结果为空，尝试查询所有数据（用于调试）
        if (result == null || result.isEmpty()) {
            log.info("未找到匹配条件的数据，尝试查询所有合同总数");
            Integer totalCount = reportMapper.countContractByDateRange(null, null);
            log.info("系统中总合同数：{}", totalCount);
        }

        return result;
    }

    @Override
    public List<HashMap<String, Object>> salesStatistic(LocalDate beginCreateTime, LocalDate endCreateTime, Integer deptId) {
        log.info("执行销售统计查询 - beginCreateTime: {}, endCreateTime: {}, deptId: {}", beginCreateTime, endCreateTime, deptId);

        // 先查询符合日期范围的合同总数
        Integer dateRangeCount = reportMapper.countContractByDateRange(beginCreateTime, endCreateTime);
        log.info("日期范围内合同总数: {}", dateRangeCount);

        // 查询符合日期范围和部门ID的合同数
        if (deptId != null) {
            List<HashMap<String, Object>> deptContracts = reportMapper.countContractByDeptId(deptId, beginCreateTime, endCreateTime);
            if (deptContracts != null && !deptContracts.isEmpty()) {
                log.info("部门{}在日期范围内的合同数: {}", deptId, deptContracts.get(0).get("count"));
            }
        }

        // 执行销售统计查询
        List<HashMap<String, Object>> result = reportMapper.salesStatistic(beginCreateTime, endCreateTime, deptId);
        log.info("销售统计查询结果数量: {}", result != null ? result.size() : 0);

        // 如果结果为空，检查系统中总合同数
        if (result == null || result.isEmpty()) {
            log.info("未找到匹配条件的数据，尝试查询所有合同总数");
            Integer totalCount = reportMapper.countContractByDateRange(null, null);
            log.info("系统中总合同数: {}", totalCount);
        }
        return result;
    }

    //线索统计 新增线索数量
    @Override
    public ReportVo cluesStatisticls(LocalDate beginCreateTime, LocalDate endCreateTime) {
        List<HashMap<String, Object>> maps = reportMapper.cluesStatisticls(beginCreateTime, endCreateTime);
        String[] time = maps.stream().map(s -> String.valueOf(s.get(Constant.TIME))).toArray(String[]::new);
        String[] add = maps.stream().map(s -> String.valueOf(s.get(Constant.ADD))).toArray(String[]::new);
        String[] total = maps.stream().map(s -> String.valueOf(s.get(Constant.TOTAL))).toArray(String[]::new);
        ReportVo reportVo = new ReportVo();
        reportVo.setXAxis(time);
        ArrayList<ReportDetailVo> vos = new ArrayList<>();
        ReportDetailVo detailVo = new ReportDetailVo();
        detailVo.setName(Constant.ADDRULES);
        detailVo.setData(add);
        ReportDetailVo detailVo1 = new ReportDetailVo();
        detailVo1.setName(Constant.COUNTRULES);
        detailVo1.setData(total);
        vos.add(detailVo);
        vos.add(detailVo1);
        reportVo.setSeries(vos);
        return reportVo;
    }

    //渠道统计 列表展示
    @Override
    public CourseContractResponseVO<ChannelVo> activityStatistics(ChannelPageDTO dto) {
        Page<ChannelVo> page = new Page<>(dto.getPageNum(), dto.getPageSize());
        Page<ChannelVo> pages = reportMapper.activityStatistics(page, dto);
        CourseContractResponseVO<ChannelVo> responseVO = new CourseContractResponseVO<>();
        log.info("返回的数据最后:{}",pages.getRecords());
        responseVO.setTotal(pages.getTotal());
        responseVO.setRows(pages.getRecords());
        responseVO.setCode(Constant.SUCCESS);
        responseVO.setMsg(Constant.MSG);
        responseVO.setParams(null);
        return responseVO;
    }

    //渠道数量
    @Override
    public List<ChaneCountlVo> chanelStatistics(LocalDate beginCreateTime, LocalDate endCreateTime) {
        return reportMapper.chanelStatistics(beginCreateTime,endCreateTime);
    }

    //活动数量
    @Override
    public List<ChaneActityVo> activityStatisticls(LocalDate beginCreateTime, LocalDate endCreateTime) {
        List<ChaneActityVo> vos = reportMapper.activityStatisticls(beginCreateTime, endCreateTime);
        System.out.println("查询到的活动统计数据：" + vos);
        return vos;
    }

    @Override
    public Integer countCluesByDateRange(LocalDate beginDate, LocalDate endDate) {
        return reportMapper.countCluesByDateRange(beginDate, endDate);
    }

    @Override
    public Integer countBusinessByDateRange(LocalDate beginDate, LocalDate endDate) {
        return reportMapper.countBusinessByDateRange(beginDate, endDate);
    }

    @Override
    public Integer countContractByDateRange(LocalDate beginDate, LocalDate endDate) {
        return reportMapper.countContractByDateRange(beginDate, endDate);
    }

    @Override
    public Integer countToFollowedClues() {
        return reportMapper.countToFollowedClues();
    }

    @Override
    public Integer countToFollowedBusiness() {
        return reportMapper.countToFollowedBusiness();
    }

    @Override
    public Integer countToAllocatedClues() {
        return reportMapper.countToAllocatedClues();
    }

    @Override
    public Integer countToAllocatedBusiness() {
        return reportMapper.countToAllocatedBusiness();
    }

    @Override
    public IndexStatisticsVO getIndexStatistics(LocalDate beginCreateTime, LocalDate endCreateTime, Integer deptId) {
        IndexStatisticsVO vo = new IndexStatisticsVO();
        
        // 设置各种统计数据
        vo.setCluesNum(reportMapper.countCluesByDateRange(beginCreateTime, endCreateTime));
        vo.setBusinessNum(reportMapper.countBusinessByDateRange(beginCreateTime, endCreateTime));
        vo.setContractNum(reportMapper.countContractByDateRange(beginCreateTime, endCreateTime));
        
        // 今日统计数据
        vo.setTodayCluesNum(reportMapper.countCluesByDateRange(LocalDate.now(), LocalDate.now()));
        vo.setTodayBusinessNum(reportMapper.countBusinessByDateRange(LocalDate.now(), LocalDate.now()));
        vo.setTodayContractNum(reportMapper.countContractByDateRange(LocalDate.now(), LocalDate.now()));
        
        // 待处理统计数据
        vo.setTofollowedCluesNum(reportMapper.countToFollowedClues());
        vo.setTofollowedBusinessNum(reportMapper.countToFollowedBusiness());
        vo.setToallocatedCluesNum(reportMapper.countToAllocatedClues());
        vo.setToallocatedBusinessNum(reportMapper.countToAllocatedBusiness());
        
        return vo;
    }
}